package com.its.us.web.controller.sys;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.its.us.web.controller.sys.base.BaseWebPaginationCURDController;
import com.its.us.web.entity.sys.Role;
import com.its.us.web.service.sys.RoleService;
import com.its.us.web.utils.Tree.TreeMenu;
import com.its.us.web.vo.sys.ResultBean;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author huguangjun
 * @className RoleController
 * @date 2020/12/3
 * @desc 9:21
 */
@Api(tags = "角色")
@Controller
@RequestMapping("role")
@Slf4j
public class RoleController extends BaseWebPaginationCURDController {
    @Resource
    private RoleService roleService;

    @RequestMapping("init")
    public String init() {
        return "role/init";
    }

    @PostMapping("list")
    @ResponseBody
    @PreAuthorize("hasPermission('/role/init','sys:role:list')")
    public ResultBean list(@RequestBody MultiValueMap<String, String> param) {
        IPage<Role> pageData;
        try {
            Map<String, Object> map = super.initParam(param);
            pageData = roleService.findByPage(map);
        } catch (Exception e) {
            log.error("角色列表错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(pageData.getTotal(), pageData.getRecords());
    }

    /**
     * 保存或更新
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "保存或更新", notes = "保存或更新操作[更新操作需要传id参数]", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "roleName", value = "角色名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "roleEn", value = "角色标识", required = true, dataType = "String")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'数据已存在.'}"),
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'数据异常.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("save")
    @ResponseBody
    @PreAuthorize("hasPermission('/role/save','sys:role:save')")
    public ResultBean save(@RequestBody Role role) {
        ResultBean resultBean;
        try {
            resultBean = roleService.saveOrUpdate(role);
        } catch (Exception e) {
            log.error("角色保存错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "详情", notes = "根据id查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "标识id", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:object}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @GetMapping("detail")
    @ResponseBody
    public ResultBean detail(@RequestParam("id") String id) {
        Role role;
        try {
            role = roleService.findById(id);
        } catch (Exception e) {
            log.error("角色查询错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(role);
    }

    /**
     * 删除
     *
     * @param ids
     * @param userName
     * @return
     */
    @ApiOperation(value = "删除", notes = "根据ids删除[可以是多个id]", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "标识id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "当前登录人", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("delete")
    @ResponseBody
    @PreAuthorize("hasPermission('/role/delete','sys:role:delete')")
    public ResultBean delete(@RequestParam("ids[]") List<String> ids, @RequestParam("userName") String userName) {
        ResultBean resultBean;
        try {
            resultBean = roleService.deleteByIds(ids, userName);
        } catch (Exception e) {
            log.error("角色删除错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }

    /**
     * role列表
     *
     * @return
     */
    @ApiOperation(value = "角色获取全部", notes = "返回所有角色数据", httpMethod = "POST")
    @ApiImplicitParams({
    })
    @PostMapping("getAllRole")
    @ResponseBody
    //@PreAuthorize("hasPermission('/role/init','sys:role:list')")
    public ResultBean getAllRole() {
        List<TreeMenu> menus;
        try {
            menus = roleService.getAllRole();
        } catch (Exception e) {
            log.error("role列表读取错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(menus);
    }

    /**
     * role列表
     * 1 角色回显使用
     *
     * @return
     */
    @ApiOperation(value = "根据用户id获取角色", notes = "返回查询角色数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "String"),
    })
    @GetMapping("getRoleByUserId")
    @ResponseBody
    //@PreAuthorize("hasPermission('/role/getRoleByUserId','sys:role:byUserId')")
    public ResultBean getRoleByUserId(@RequestParam("userId") String userId) {
        List<Role> roles;
        try {
            roles = roleService.getRoleByUserId(userId);
        } catch (Exception e) {
            log.error("根据用户id表读角色数据取错误：", e);
            return new ResultBean(e.getCause());
        }
        return new ResultBean(roles);
    }


    /**
     * 角色授权菜单
     *
     * @param menuIds
     * @param roleId
     * @return
     */
    @ApiOperation(value = "角色授权菜单", notes = "角色授权菜单", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "menuIds", value = "菜单ids", required = true, dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "{code:0,msg:'success',data:'操作成功.'}"),
            @ApiResponse(code = -99, message = "{code:-99,msg:'fail',data:'打印错误'}")
    })
    @PostMapping("authMenu")
    @ResponseBody
    //@PreAuthorize("hasPermission('/role/authRole','sys:role:authRole')")
    public ResultBean authMenu(@RequestParam("menuIds[]") List<String> menuIds, @RequestParam("roleId") String roleId){
        ResultBean resultBean;
        try {
            resultBean = roleService.authMenu(menuIds,roleId);
        }catch (Exception e){
            log.error("角色授权菜单出现错误：", e);
            return new ResultBean(e.getCause());
        }
        return resultBean;
    }


}
